package com.leo.slice;

import com.leo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.webengine.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.multimodalinput.event.KeyEvent;
import ohos.net.http.SslError;

public class WikiAbilitySlice extends AbilitySlice {
    String urlStr;
    private WebView webView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_wiki);
        webView = (WebView) findComponentById(ResourceTable.Id_webView);
        ProgressBar progressBar = (ProgressBar) findComponentById(ResourceTable.Id_progressBar);
        findComponentById(ResourceTable.Id_shadowLayout_bar_left).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Navigator navigator = webView.getNavigator();
                if (navigator.canGoBack()) {
                    navigator.goBack();
                } else {
                    terminate();
                }
            }
        });

        //        urlStr = "https://github.com/lihangleo2";
        urlStr = "https://gitee.com/ts_ohos/shadowLayout/wikis";
        //声明WebSettings子类
        WebConfig webSettings = webView.getWebConfig();

        webSettings.setJavaScriptPermit(true);
        //设置自适应屏幕，两者合用
        webSettings.setViewPortFitScreen(true); //将图片调整到适合webview的大小
        webSettings.setTextAutoSizing(true); // 缩放至屏幕的大小
        webSettings.setWebStoragePermit(true);

        //缩放操作
//        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
//        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
//        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
//        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //开启缓存LOAD_CACHE_ELSE_NETWORK//LOAD_NO_CACHE关闭缓存
        webSettings.setSecurityMode(WebConfig.SECURITY_ALLOW); //设置可以访问文件
//        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesPermit(true); //支持自动加载图片
//        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式


//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            //解决webView不加载图片
//            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//        }


        ////步骤3. 复写shouldOverrideUrlLoading()方法，使得打开网页时不调用系统浏览器， 而是在本WebView中显示
        webView.setWebAgent(new WebAgent() {
            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                String url = request.getRequestUrl().toString();
                try {
                    if (url.startsWith("http:") || url.startsWith("https:")) {
                        webView.load(url);
                        return false;
                    } else {
//                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) {
                    return true;
                }
            }

            @Override
            public void onError(WebView webView, ResourceRequest request, ResourceError error) {
                if (progressBar != null) {
                    progressBar.setVisibility(Component.HIDE);
                }
                new ToastDialog(getContext()).setText("网页加载失败").show();
            }

            @Override
            public void onSslError(WebView webView, SslError error) {
                super.onSslError(webView, error);
            }

            //webView加载结束后的动作
            @Override
            public void onPageLoaded(WebView webView, String url) {
                if (progressBar != null) {
                    progressBar.setVisibility(Component.HIDE);
                }
            }
        });

        webView.setBrowserAgent(new BrowserAgent(getContext()) {
            @Override
            public void onProgressUpdated(WebView webView, int newValue) {
                if (progressBar.getVisibility() == Component.HIDE && newValue != 100) {
                    //点击webView内部，进度条可见
                    progressBar.setVisibility(Component.VISIBLE);
                }

                if (newValue == 100 && progressBar.getVisibility() == Component.VISIBLE) {
                    //bug:不走finish所以不能设置不可见
                    progressBar.setVisibility(Component.HIDE);
                }

                if (progressBar != null) {
                    progressBar.setProgressValue(newValue);
                }
            }
        });

        webView.load(urlStr);
        //js互调相关
        webView.addJsCallback("JSbridge", new JsCallback() {
            @Override
            public String onCallback(String s) {
                return null;
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEY_BACK && webView.getNavigator().canGoBack()) {
            webView.getNavigator().goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, keyEvent);
    }

    @Override
    public void onActive() {
        super.onActive();
        if (webView != null) {
            webView.onActive();
        }
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        if (webView != null) {
            webView.onInactive();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (webView != null) {
            webView.onStop();
        }
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
